package com.mall.gateway.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * Sa-Token网关配置
 */
@Configuration
public class SaTokenConfig {
    
    /**
     * 注册Sa-Token上下文过滤器
     */
    @Bean
    public WebFilter saTokenContextFilter() {
        return new WebFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
                // 将请求上下文保存到当前线程
                return Mono.fromCallable(() -> {
                    SaReactorSyncHolder.set(exchange);
                    return exchange;
                }).flatMap(ex -> chain.filter(ex)).doFinally(signalType -> {
                    SaHolder.clear();
                });
            }
        };
    }
} 